import _ from 'lodash'

export const timeFormat = {
  mounted(el, binding, vnode) {

    updateTime(el, binding, vnode)
  },
  updated(el, binding, vnode) {
    updateTime(el, binding, vnode)
  },
}

function updateTime(el, binding, vnode) {
  const value = binding.value
  const format = vnode.props.format || 'yyyy-MM-dd'
  if (_.isString(value) || _.isNumber(value)) {
    el.textContent = formatTimeValue(value, format)
  } else {
  }
}

function formatTimeValue(value, format) {
  let parsedDate

  if (_.isString(value)) {
    parsedDate = new Date(Date.parse(value))
  } else if (_.isNumber(value)) {
    // 如果时间戳是10位，则将其乘以1000转换为毫秒级时间戳
    parsedDate = new Date(value * (value.toString().length === 10 ? 1000 : 1))
  } else {
    return ''
  }

  if (isNaN(parsedDate.getTime())) {
    return ''
  }

  const map = {
    yyyy: parsedDate.getFullYear(),
    MM: ('0' + (parsedDate.getMonth() + 1)).slice(-2),
    dd: ('0' + parsedDate.getDate()).slice(-2),
    HH: ('0' + parsedDate.getHours()).slice(-2),
    mm: ('0' + parsedDate.getMinutes()).slice(-2),
    ss: ('0' + parsedDate.getSeconds()).slice(-2),
  }

  return format.replace(/yyyy|MM|dd|HH|mm|ss/g, (match) => map[match])
}
